import { useDataStore } from '@/stores/userDataStore'
import { useJoinStore } from '@/stores/joinStote'
import { gameStores } from '@/stores/gameStores'
import { wsUrl } from '@/util/BASE_API'
import router from '@/router'

const useData = useDataStore()
const JoinStore = useJoinStore()
const gameStore = gameStores()
const WebSocketType = {
    Error: 0, //错误
    GroupChat: 1,
    SingleChat: 2,
    Position: 3, //我的大厅位置
    AllPositions: 4, //所有人大厅位置
}

let ws = null
let msg = null

const openWS = () => {
    ws = new WebSocket(`${wsUrl}?id=${useData.userId}`)

    ws.onopen = () => {
        useData.getWS = true
    }

    ws.onmessage = async (msgObj) => {
        msgObj = JSON.parse(msgObj.data)
        console.log("msgObj " + msgObj)
        switch (msgObj.type) {
            case WebSocketType.Position: //我的位置
                useData.position = msgObj
                break
            case WebSocketType.AllPositions: // 在线用户列表
                useData.onlineUserList = msgObj
                break
            case WebSocketType.GroupChat: //群聊
                // eslint-disable-next-line no-case-declarations
                let title = msgObj.user ? msgObj.user.username : '广播'
                console.log(title + ' : ' + msgObj.data)
                break
            case WebSocketType.SingleChat:
                msg = JSON.parse(msgObj.data)
                if (msg.type === 'join') {
                    JoinStore.getInvite = true
                } else if (msg.type === 'no') {
                    //拒绝邀请（接收方）
                    JoinStore.sendInvite = false
                } else if (msg.type === 'Cancel') {
                    //取消邀请（发送方）
                    JoinStore.getInvite = false
                } else if (msg.type === 'OK') {
                    //对方接受邀请（发送方）
                    JoinStore.sendInvite = false
                    gameStore.InGame = true
                    await router.push('/gaming')
                } else if (msg.type === 'draw') {
                    //双方
                    gameStore.enemyDraw = msg.inf
                } else if (msg.type === 'lose') {
                    //对方输了
                    gameStore.win = 1
                }
                break
        }
    }

    ws.onerror = (err) => {
        console.log(err)
    }
}

/**
 * 发送消息
 * @param type 类型 0错误 1群发 2群聊 3私聊
 * @param data 数据
 * @param to 发送给谁
 */
const send = (type, data, to) => {
    if (ws?.readyState === WebSocket.OPEN) {
        //判断是否连接
        ws.send(createMessage(type, data, to))
    }
}

/**
 * 创建发送的消息
 * @param type 类型 0错误 1群发 2群聊 3私聊
 * @param data 数据
 * @param to 发送给谁（type为3时有效）
 * @returns {string} 字符串
 */
const createMessage = (type, data, to) => {
    return JSON.stringify({
        type,
        data,
        to,
    })
}

export { openWS, send }
